package com.ms.teapuesto.jsf.converter;

import com.ms.teapuesto.bean.LigaBean;
import com.ms.teapuesto.model.Liga;
import com.ms.teapuesto.persistence.jpa.LigaRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import java.util.List;

/**
 * Created by JAVA on 28/10/2014.
 */
@Component
@FacesConverter("com.ms.teapuesto.jsf.converter.LigaBeanConverter")
public class LigaBeanConverter implements Converter {
    @Autowired
    protected LigaRepository ligaRepository;



    public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        if (StringUtils.isBlank(value) || value.equals("Seleccione")|| value.equals("Todos")) {
            return null;
        }
        Liga liga= ligaRepository.findOne(value);
        LigaBean result= new LigaBean();
        BeanUtils.copyProperties(liga,result);
        return result;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
        if (value == null || !(value instanceof LigaBean) ) {
            return null;
        }
        return String.valueOf(((LigaBean)value).getNombre());
    }
}
